//
#include "main_controller.h"
#include <iostream>
#include <vector>
#include <thread>
#include "data_source.h"
#include "tsp.h"
#include "data_center.h"

MainController::MainController() {
    cfar_address = "tcp://192.168.1.115:5006";
    cfar_socket = zmq::socket_t(context, zmq::socket_type::req);
    cfar_socket.connect(cfar_address);
}

MainController::~MainController() {
    cfar_socket.close();
}

int MainController::startup() {
    std::cout << "启动系统" << std::endl;
    std::string sourceTopicHost = "tcp://192.168.1.115:5001";
    std::string sourceTopic = "sourceTopic";
    std::string pcPushAddr = "tcp://192.168.1.115:5002";
    std::string mtiPushAddr = "tcp://192.168.1.115:5003";
    std::string mtdPushAddr = "tcp://192.168.1.115:5004";
    std::string cfarPushAddr = "tcp://192.168.1.115:5005";
    DataSource dataSource(sourceTopicHost, sourceTopic);
    // 启动各个模块的线程
    std::vector<std::thread> threads;
    threads.emplace_back(&DataSource::mainLoop, &dataSource);
    PC pc(sourceTopicHost, sourceTopic, pcPushAddr);
    threads.emplace_back(&PC::startup, &pc);
    MTI mti(pcPushAddr, mtiPushAddr);
    threads.emplace_back(&MTI::startup, &mti);
    MTD mtd(mtiPushAddr, mtdPushAddr);
    threads.emplace_back(&MTD::startup, &mtd);
    CFAR cfar(mtdPushAddr, cfar_address);
    threads.emplace_back(&CFAR::startup, &cfar);
    float cfar_threshold = 0.01;
    DataCenter dataCenter(sourceTopicHost, sourceTopic);
    threads.emplace_back(&DataCenter::startup, &dataCenter);
    while (true) {
        std::this_thread::sleep_for(std::chrono::milliseconds(1000));
        std::cout << "通过REQ更新CFAR的阈值，DataCenter监听DataSource数据..." << std::endl;
        zmq::message_t request(sizeof(float));
        memcpy(request.data(), &cfar_threshold, sizeof(float));
        cfar_socket.send(request, zmq::send_flags::none);
        zmq::message_t response;
        cfar_socket.recv(response, zmq::recv_flags::none);
        float ack;
        memcpy(&ack, response.data(), sizeof(float));
        std::cout << "        CFAR threshold set to: " << ack << std::endl;
        cfar_threshold += 0.01;
    }
    // 等待模块完成
    for (auto& t : threads) {
        if (t.joinable()) {
            t.join();
        }
    }
    return 0;
}